<template>
  <div class="payment-view">
    <van-nav-bar
        title="支付"
        left-arrow
        @click-left="onClickLeft"
        fixed
    />

    <div class="payment-form">
      <!-- 配件选择部分 -->
      <div class="form-item">
        <div class="form-label">配件选择：</div>
        <div class="parts-list">
          <div v-for="(part, index) in parts" :key="index" class="part-item">
            <div class="part-info">
              <van-field
                  v-model="part.name"
                  placeholder="请输入配件名称"
                  class="part-name"
              />
              <div class="price-quantity">
                <van-field
                    v-model="part.price"
                    type="number"
                    placeholder="单价"
                    class="part-price"
                    @input="calculateTotal"
                >
                  <template #right-icon>
                    <span class="unit">元</span>
                  </template>
                </van-field>
                <div class="quantity-control">
                  <span>数量：</span>
                  <van-stepper v-model="part.quantity" min="0" @change="calculateTotal"/>
                </div>
              </div>
            </div>
            <van-icon
                name="cross"
                class="delete-part"
                @click="removePart(index)"
            />
          </div>
        </div>
        <van-button size="small" icon="plus" class="add-part" @click="addPart">添加配件</van-button>
      </div>

      <!-- 人工费用 -->
      <div class="form-item">
        <div class="form-label">人工费合计：</div>
        <van-field
            v-model="laborCost"
            type="number"
            placeholder="请输入人工费用"
            @input="calculateTotal"
        >
          <template #right-icon>
            <span class="unit">元</span>
          </template>
        </van-field>
      </div>

      <!-- 其他费用 -->
      <div class="form-item">
        <div class="form-label">其他费用：</div>
        <van-field
            v-model="otherCost"
            type="number"
            placeholder="请输入其他费用"
            @input="calculateTotal"
        >
          <template #right-icon>
            <span class="unit">元</span>
          </template>
        </van-field>
      </div>

      <!-- 备注 -->
      <div class="form-item">
        <div class="form-label">备注：</div>
        <van-field
            v-model="remark"
            type="textarea"
            rows="3"
            placeholder="请填写相关备注信息"
        />
      </div>

      <!-- 总计金额展示 -->
      <div class="total-amount">
        <span>总计金额：</span>
        <span class="amount">¥ {{ totalAmount.toFixed(2) }}</span>
      </div>

      <!-- 支付按钮 -->
      <div class="submit-btn">
        <van-button type="primary" block @click="handlePayment">立即支付</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { NavBar, Field, Button, Stepper, Toast, Icon } from 'vant';

export default {
  name: 'PaymentView',
  components: {
    [NavBar.name]: NavBar,
    [Field.name]: Field,
    [Button.name]: Button,
    [Stepper.name]: Stepper,
    [Icon.name]: Icon,
  },
  data() {
    return {
      parts: [
        {name: '', price: 40, quantity: 1},
      ],
      laborCost: '200',
      otherCost: '10',
      remark: '',
      totalAmount: 0,
      formData: {
        orderNo: '', // 订单号
        totalAmount: 0, // 总金额
        payType: 'alipay', // 支付方式
        subject: '医疗设备维修费用', // 订单标题
      }
    }
  },
  methods: {
    onClickLeft() {
      this.$router.back()
    },
    addPart() {
      this.parts.push({
        name: '',
        price: 0,
        quantity: 1
      });
      this.$nextTick(() => {
        this.calculateTotal();
      });
    },
    removePart(index) {
      this.parts.splice(index, 1);
      this.$nextTick(() => {
        this.calculateTotal();
      });
    },
    calculateTotal() {
      let partsTotal = this.parts.reduce((sum, part) => {
        const price = parseFloat(part.price) || 0;
        const quantity = parseInt(part.quantity) || 0;
        return sum + (price * quantity);
      }, 0);

      let labor = parseFloat(this.laborCost) || 0;
      let other = parseFloat(this.otherCost) || 0;

      this.totalAmount = partsTotal + labor + other;
      // 同步更新支付表单的总金额
      this.formData.totalAmount = this.totalAmount;
    },
    handlePayment() {
      if (this.parts.some(part => !part.name.trim())) {
        Toast('请填写所有配件名称');
        return;
      }
      if (this.parts.some(part => !part.price || part.price <= 0)) {
        Toast('请填写正确的配件价格');
        return;
      }
      if (this.totalAmount <= 0) {
        Toast('支付金额必须大于0');
        return;
      }

      // 准备支付数据
      this.formData.orderNo = 'ORDER' + Date.now(); // 生成订单号
      this.formData.totalAmount = this.totalAmount;

      Toast.loading({
        message: '正在创建支付订单...',
        forbidClick: true,
      });

      // 调用支付宝接口
      this.axios.post('http://localhost:9999/api-alipay-service/alipay/create', this.formData)
          .then(async res => {
            if (res.data) {
              // 创建一个临时div来显示支付宝返回的表单
              const div = document.createElement('div');
              div.innerHTML = res.data;
              document.body.appendChild(div);

              // 自动提交表单到支付宝
              document.forms[0].submit();
            } else {
              Toast.fail('创建支付订单失败');
            }
          })
          .catch(err => {
            console.error('支付失败:', err);
            Toast.fail('支付失败，请重试');
          });
    }
  },
  mounted() {
    this.calculateTotal();
  },
  watch: {
    parts: {
      deep: true,
      handler() {
        this.calculateTotal();
      }
    },
    laborCost() {
      this.calculateTotal();
    },
    otherCost() {
      this.calculateTotal();
    },
    totalAmount(newVal) {
      // 确保支付表单的总金额同步更新
      this.formData.totalAmount = newVal;
    }
  }
}
</script>

<style scoped>
.payment-view {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-top: 46px;
}

.payment-form {
  padding: 16px;
}

.form-item {
  background: #fff;
  padding: 16px;
  margin-bottom: 12px;
  border-radius: 8px;
}

.form-label {
  margin-bottom: 8px;
  font-size: 14px;
  color: #323233;
  font-weight: bold;
}

.parts-list {
  margin-bottom: 12px;
}

.part-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
  padding: 12px;
  background: #f7f8fa;
  border-radius: 8px;
}

.part-info {
  flex: 1;
  margin-right: 12px;
}

.part-name {
  margin-bottom: 8px;
}

.price-quantity {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.part-price {
  width: 100px;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-control span {
  white-space: nowrap;
  margin-right: 8px;
  font-size: 14px;
}

.delete-part {
  padding: 4px;
  color: #969799;
  cursor: pointer;
}

.delete-part:hover {
  color: #ee0a24;
}

:deep(.van-field) {
  padding: 0;
  background: transparent;
}

:deep(.van-stepper) {
  margin-left: 0;
}

:deep(.van-field__control) {
  text-align: left;
}

:deep(.van-field__body) {
  min-height: 24px;
  display: flex;
  align-items: center;
}

.add-part {
  width: 100%;
  margin-top: 8px;
}

.unit {
  color: #969799;
  margin-left: 4px;
}

.total-amount {
  background: #fff;
  padding: 16px;
  margin-bottom: 12px;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
}

.amount {
  color: #ee0a24;
  font-size: 20px;
  font-weight: bold;
}

.submit-btn {
  margin-top: 24px;
  padding: 0 16px;
}

:deep(.van-field__control) {
  text-align: right;
}

:deep(.van-stepper) {
  margin-left: auto;
}

:deep(.van-button--primary) {
  background: #1989fa;
  border-color: #1989fa;
}
</style>